package mynet

import (
	"GoPro/Server/msgProto"
	"bufio"
	"encoding/binary"
	"net"
)

type connection struct {
	reader   *bufio.Reader
	writer   net.Conn
	exitChan chan bool
	conId    int
	serv     *Server
}

func (this *connection) GetConId() int {
	return this.conId
}

func (this *connection) GetReader() *bufio.Reader {
	return this.reader
}

func (this *connection) Start() {
	go func() {
		header := msgProto.MsgHeader{}
		var data []byte
		for {
			err := binary.Read(this.reader, binary.BigEndian, &header)
			if err != nil {
				this.exitChan <- true
				break
			}
			if header.MsgSize != 0 {
				data = make([]byte, header.MsgSize)
				err = binary.Read(this.reader, binary.BigEndian, data)
				if err != nil {
					this.exitChan <- true
					break
				}
			}
			request := &Request{this, header.MsgType, data, this.serv}
			//fmt.Println(string(data))
			this.serv.msgHandler.SendTaskToWork(request)
		}
	}()
	<-this.exitChan
	close(this.exitChan)
	this.writer.Close()
	this.serv.clientManager.Del(this.GetConId())
}

func (this *connection) GetExitChan() chan bool {
	return this.exitChan
}

func (this *connection) GetWriter() net.Conn {
	return this.writer
}

func GetNewConnection(conId int, client net.Conn, serv *Server) IConnection {
	return &connection{
		conId:    conId,
		reader:   bufio.NewReader(client),
		exitChan: make(chan bool),
		serv:     serv,
		writer:   client,
	}

}
